package com.hmyd.hmyd_android.shop;

import java.util.ArrayList;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hmyd.hmyd_android.R;
import com.hmyd.hmyd_android.AppBasic;
import com.hmyd.hmyd_android.adapter.MyOrderAdapter;
import com.hmyd.hmyd_android.adapter.MyOrderAdapter.OnConfirmListener;
import com.hmyd.hmyd_android.commons.UrlConstant;
import com.hmyd.hmyd_android.dto.DtoInfoNoPage;
import com.hmyd.hmyd_android.dto.InfoDto;
import com.hmyd.hmyd_android.dto.MyOrder;
import com.hmyd.hmyd_android.dto.Page;
import com.hmyd.hmyd_android.dto.Score;
import com.hmyd.hmyd_android.ui.BasicListActivity;
import com.hmyd.hmyd_android.ui.LoginActivity;
import com.hmyd.hmyd_android.utils.MyToast;
import com.hmyd.hmyd_android.utils.Utils;
import com.hmyd.hmyd_android.view.listview.XListView;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;

/**
 * 我的订单
 * 
 * @author wangk
 * 
 */

@ContentView(R.layout.activity_my_order)
public class MyOrderActivity extends BasicListActivity implements OnConfirmListener {

	private Context mContext;
	private XListView mXListView;
	private MyOrderAdapter mAdapter;
	private ArrayList<MyOrder> datas = new ArrayList<MyOrder>();

	private final int REFRESH = 1;
	private final int LOADMORE = 2;
	private final int CONFIRM = 3;
	private final int GETMYSCORE = 4;

	protected boolean hasMore = false;
	private long cursorId;
	private int postion = 0;

	private LinearLayout conLayout;
	private boolean isFromMyShop = false;
	
	@ViewInject(R.id.home_title_txt)
	private TextView home_title_txt;
	@ViewInject(R.id.home_title)
	private View home_title;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if(keyCode == KeyEvent.KEYCODE_BACK) {
			AppBasic.getInstance().finishCurrentActivity();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	protected void setParams() {
		home_title_txt.setText("我的订单");
		initViews();
		onRequest();
	}


	@Override
	protected void leftButton() {
		AppBasic.getInstance().finishCurrentActivity();
	}

	private void onRequest() {
		onRequest(REFRESH, UrlConstant.ORDERLIST, HttpMethod.GET, null);
		onRequest(GETMYSCORE, UrlConstant.GETMYSCORE, HttpMethod.GET, null);
	}

	private void initViews() {
		home_title.setOnTouchListener(touch);
		mContext = this;
		mXListView = (XListView) findViewById(R.id.list);
		mXListView.setPullRefreshEnable(true); // 允许下拉刷新
		mXListView.setPullLoadEnable(false); // 禁止加载更多
		mXListView.setAutoLoadEnable(false); // 禁止自动加载
		mXListView.setXListViewListener(this);// 加载监听

		mAdapter = new MyOrderAdapter(mContext, datas);
		mXListView.setAdapter(mAdapter);

		conLayout = (LinearLayout) findViewById(R.id.content);

		isFromMyShop = getIntent().getBooleanExtra("fromMyShop", false);

	}

	public XListView getXList() {
		return mXListView;
	}

	@Override
	protected void onResume() {
		super.onResume();
		onRequest(REFRESH, UrlConstant.ORDERLIST, HttpMethod.GET, null);
	}

	@Override
	public void onRefresh() {
		super.onRefresh();

		onRequest(REFRESH, UrlConstant.ORDERLIST, HttpMethod.GET, null);
	}

	@Override
	public void onLoadMore() {
		super.onLoadMore();

		RequestParams params = new RequestParams();
		params.addBodyParameter("lastCursor", String.valueOf(cursorId));

		onRequest(LOADMORE, UrlConstant.ORDERLIST, HttpMethod.GET, params);

	}

	@Override
	public void onPostSuccess(int postId, String result) {
		super.onPostSuccess(postId, result);
		Gson gson = new Gson();
		
		switch (postId) {
		case GETMYSCORE:
			java.lang.reflect.Type type2 = new TypeToken<Score>() {
			}.getType();
			Score score = gson.fromJson(result, type2);
			AppBasic.totalScore = score.score;
			break;
		case CONFIRM:
			java.lang.reflect.Type type3 = new TypeToken<DtoInfoNoPage<InfoDto>>() {
			}.getType();
			DtoInfoNoPage<InfoDto> dtoInfoNoPage1 = gson.fromJson(result, type3);
			if(dtoInfoNoPage1.suc == 1011) {
				datas.get(postion).state = "Completed";
				mAdapter.notifyDataSetChanged();
				MyToast.showHMToast(MyOrderActivity.this, true, "恭喜兑换成功");
			} else {
				MyToast.showHMToast(MyOrderActivity.this, false,
						dtoInfoNoPage1.errmsg);
			}
			break;
		default:
				java.lang.reflect.Type type4 = new TypeToken<DtoInfoNoPage<Page<MyOrder>>>() {
				}.getType();
				final DtoInfoNoPage<Page<MyOrder>> dtoInfoNoPage2 = gson.fromJson(result, type4);
				final Page<MyOrder> page = dtoInfoNoPage2.data;
				hasMore = page.hasMore;
				if (page != null && page.records != null) {
					switch (postId) {
					case REFRESH:
						datas.clear();
						datas.addAll(page.records);
						break;
					case LOADMORE:
						datas.addAll(page.records);
						break;
					default:
						break;
					}
					if (datas.size() > 0) {
						cursorId = datas.get(datas.size() - 1).createdTime;
					} else {
						cursorId = 0;
					}
					mAdapter.notifyDataSetChanged();
				break;
			}
		}
	}

	@Override
	public void onPostFailure(int postId, String msg) {
		super.onPostFailure(postId, msg);

		if (getXList() != null && hasMore) {
			getXList().setPullLoadEnable(true);
		} else if (getXList() != null && !hasMore) {
			getXList().setPullLoadEnable(false);
		}
	}
	

	// 确认收货
	@Override
	public void onConfirm(String id, int postion, String state) {
		this.postion = postion;
		RequestParams params = new RequestParams();
		params.addBodyParameter("itemId", id);
		onRequest(CONFIRM, UrlConstant.ORDER_COMFIRN, HttpMethod.POST, params);
	}
	
	// 查看详情
	@Override
	public void onDetail(String Id, String state) {
		Intent intent = new Intent();
		intent.putExtra("id", Id);
		intent.putExtra("state", state);
		intent.setClass(mContext, OrderDetailsActivity.class);
		startActivity(intent);
	}
	
	/**
	 * 添加 Home Title 触摸监听事件（必须要添加在子类中）
	 */
	protected OnTouchListener touch = new OnTouchListener() {

		@Override
		public boolean onTouch(View v, MotionEvent event) {
			int X = (int) event.getX();
			if (X < Utils.screenWidth_ / 5) {
				leftButton();
			} else if (X > Utils.screenWidth_ * 4 / 5) {
				rightButton();
			}
			return false;
		}
	};

	
}
